package vn.com.tiz.DocumentZ.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;

import vn.com.tiz.DocumentZ.R;
import vn.com.tiz.DocumentZ.view.BookPageView;
import vn.com.tiz.DocumentZ.view.BookView;
import vn.com.tiz.DocumentZ.view.VerticalViewSwitcher;
import vn.com.tiz.DocumentZ.view.WipeView;
import vn.com.tiz.DocumentZ.view.WipeView.OnScreenSwitchListener;
import vn.com.tiz.bookcase.task.LoadContentTask;
import vn.com.tiz.core.AppSetting;
import vn.com.tiz.core.TizActivity;
import vn.com.tiz.core.task.TaskResultCallback;

import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class actBookViewer extends TizActivity{

	ArrayList<String> pages;
	boolean FlipPageMode = true;	
	private String tempContent;
	private int MaxLine = 33;
	//private ArrayList<String> lines = new ArrayList<String>();
	
	private int ChapterCount = 10;
	private int PageIndex = 0;
	private int ChapterIndex= 9;
	private WipeView mainview;
	
	private int lastPageCount = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setNoTitleBar(true);
		pages = new ArrayList<String>();
		
		mainview = new WipeView(this);
		BookPageView begin_page = new BookPageView(this);
		begin_page.setBackgroundResource(R.drawable.coverbook);		
		mainview.addView(begin_page);
		
		int height = begin_page.getTextHeight();
		int maxline = (int)((1134-20)/height);
		Log.d("TrungTT","Text Height:"+height+" Screeen Height:"+AppSetting.SCREEN_HEIGHT+" max line:"+maxline);
		MaxLine = maxline-1;
		
		BookPageView index_page = new BookPageView(this);				
		mainview.addView(index_page);
		setContentView(mainview);
		
		mainview.setOnScreenSwitchListener(new OnScreenSwitchListener() {
			
			public void onScreenSwitched(int screen) {
				// TODO Auto-generated method stub
				Log.e("TrungTT","Screen:"+(screen-1));
				int page = screen - 2;
				int max = pages.size();
				
				if(page==(max-3)){
					loadNextChapter();
				}
			}
					
		});
		loadNextChapter();		
		
		Log.d("TrungTT","end oncreate,height of page:"+begin_page.getHeightOfPage());
	}
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}
	
	private void loadNextBookChapter(){
		LoadContentTask bookLoad = new LoadContentTask(this);
		bookLoad.setCallback(new TaskResultCallback<Integer>() {
			
			public void onCallback(Integer result) {
				// TODO Auto-generated method stub
				
			}
		});
		bookLoad.execute();
	}
		
	private void loadNextChapter(){
		ChapterIndex++;
		if(ChapterIndex > ChapterCount){
			Log.d("TrungTT","Has reach last chapter !");
		}else{
			//ChapterIndex++;
			String strChapter = "chapter_"+ChapterIndex+".txt";
			Log.d("TrungTT","start load chapter "+ChapterIndex);
		
			ArrayList<String> chapterlines = new ArrayList<String>();
			AssetManager assets = getAssets();	
			try {
			
				InputStreamReader reader = new InputStreamReader(assets.open(strChapter), "UTF-8");
				BufferedReader br = new BufferedReader(reader); 
				String line;				
				while ((line = br.readLine()) != null) {
					chapterlines.add(line);
				}						
				Log.d("TrungTT","Total:"+chapterlines.size()+" lines.");
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			parseIntoPages(chapterlines);
			
			for(String str:pages){
				
				BookPageView page = new BookPageView(this);
				page.loadContent(str);
				mainview.addView(page);
			}
		}
		
		
		
		
		lastPageCount = pages.size();
	}
	
	
	
	
	public void parseIntoPages(ArrayList<String> lines){
		String strPage = "";
		int count = 0;
		//MaxLine = 32;
		for(String str:lines){
			if(str.trim().length() == 0){
				//strPage+="\n";
				count++;
			}else{
			
				ArrayList<String> arr = wrapText1(str,AppSetting.SCREEN_WIDTH - 30);			
				for(String s:arr){
					
					strPage +=s;
					count++;
					if(count == MaxLine){
						pages.add(strPage);
						count = 0;
						strPage = "";
					}
				}
			}
			
			strPage +="\n";
			//count++;
			if(count == MaxLine){
				pages.add(strPage);
				count = 0;
				strPage = "";
			}
		}
		
		//Last page.
		if(strPage.length() >0){
			pages.add(strPage);
			count = 0;
			strPage = "";
		}
		Log.d("TrungTT","total page:"+pages.size());
	}
	
	public ArrayList<String> wrapText1(String text,int displayWidth){
		
		TextView txv = new TextView(this);
		int start = 0;
		int end  = 0;
		ArrayList<String> result = new ArrayList<String>();
		//Log.e("TrungTT","---------- wrap for text:"+text+" ------------");
		//int lineCount = 0;
		String temp = "";
		for(int i=0;i<text.length();i++){
			//String temp += text.
			//end++;
			end = i;
			float w = txv.getPaint().measureText(text, start, end);
			if(w >= displayWidth){
				try {
														
					temp = text.substring(start, end);
					char lastchar = temp.charAt(temp.length()-1);
					//Log.i("TrungTT","last char:"+lastchar+" of text:"+temp);
					//Log.v("TrungTT","truoc khi xu ly :"+temp+" star:"+start+" ,end:"+end+" len:"+text.length());
					if(lastchar == ' '){
						//Log.i("TrungTT","no need process:"+temp);
						temp = text.substring(start, end);
						result.add(temp);
						start = end;
					}else{
						//tiem ky tu ' ' cuoi cung roi tach chuoi ra.
						//Log.i("TrungTT","need process:"+temp);
						int lastWord = end;
						
						for(int j=(temp.length()-1);j>0;j--){
							if(temp.charAt(j) == ' '){
								lastWord = j;
								break;
							}
						}
						
						//Log.v("TrungTT","last word:"+lastWord);
						//temp  = text.substring(start, lastWord);
						temp  = temp.substring(0, lastWord);
						result.add(temp);
						//end = lastWord;
						start += lastWord;
						//Log.v("TrungTT","sau khi xu ly :"+temp+" star:"+start+" ,end:"+end+" len:"+text.length());
						if(end == (text.length()-1)){
							temp = text.substring(start);
							result.add(temp);
							break;
						}
						//end++;
					}
				
					
					//String temp = text.substring(start, end);
//					start = end;
//					if(start>=text.length()){
//						break;
//					}
					//Log.v("TrungTT","wrap line():"+temp);
					//result.add(temp);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("TrungTT","end:"+end+" len:"+text.length());
					//Log.e("TrungTT","text:"+text);
				}
				
				
			}else{
				if(i == (text.length()-1)){				
					temp = text.substring(start);
					result.add(temp);
					//Log.v("TrungTT","end text:"+temp+" start:"+start);
				}
				
				
				
			}
		}
		
		//print result
//		for(String s:result){
//			Log.v("TrungTT","wrap line:"+s);
//		}
		return result;
	}
	
	
	
	public String[] wrapText (String text, int len)
	{
	  // return empty array for null text
	  if (text == null)
	  return new String [] {};

	  // return text if len is zero or less
	  if (len <= 0)
	  return new String [] {text};

	  // return text if less than length
	  if (text.length() <= len)
	  return new String [] {text};

	  char [] chars = text.toCharArray();
	  Vector<String> lines = new Vector<String>();
	  StringBuffer line = new StringBuffer();
	  StringBuffer word = new StringBuffer();

	  for (int i = 0; i < chars.length; i++) {
	    word.append(chars[i]);

	    if (chars[i] == ' ') {
	      if ((line.length() + word.length()) > len) {
	        lines.add(line.toString());
	        line.delete(0, line.length());
	      }

	      line.append(word);
	      word.delete(0, word.length());
	    }
	  }

	  // handle any extra chars in current word
	  if (word.length() > 0) {
	    if ((line.length() + word.length()) > len) {
	      lines.add(line.toString());
	      line.delete(0, line.length());
	    }
	    line.append(word);
	  }

	  // handle extra line
	  if (line.length() > 0) {
	    lines.add(line.toString());
	  }

	  String [] ret = new String[lines.size()];
	  int c = 0; // counter
	  for (Enumeration<String> e = lines.elements(); e.hasMoreElements(); c++) {
	    ret[c] = (String) e.nextElement();
	  }

	  return ret;
	}
	
	
	
	private void verticalMode(){
//		String str = getResources().getString(R.string.page0);
//		VerticalViewSwitcher mainview = new VerticalViewSwitcher(this);
//		
//		
//		BookPageView begin_page = new BookPageView(this);
//		begin_page.setBackgroundResource(R.drawable.coverbook);
//		
//		BookPageView page = new BookPageView(this);
//		page.loadContent(str);
//		
//		String str1 = getResources().getString(R.string.page1);
//		BookPageView page1 = new BookPageView(this);
//		page1.loadContent(str1);
//		
//		String str2 = getResources().getString(R.string.page2);
//		BookPageView page2 = new BookPageView(this);
//		page2.loadContent(str2);
//		
//		String str3 = getResources().getString(R.string.page3);
//		BookPageView page3 = new BookPageView(this);
//		page3.loadContent(str3);
//		
//		String str4 = getResources().getString(R.string.page4);
//		BookPageView page4 = new BookPageView(this);
//		page4.loadContent(str4);
//		
//		mainview.addView(begin_page);
//		mainview.addView(page);
//		mainview.addView(page1);
//		mainview.addView(page2);
//		mainview.addView(page3);
//		mainview.addView(page4);
//		
//		setContentView(mainview);
	}
}
